package com.augmentum.oes.controller;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.augmentum.oes.Constants;
import com.augmentum.oes.exception.ParameterException;
import com.augmentum.oes.exception.ServiceException;
import com.augmentum.oes.model.User;
import com.augmentum.oes.service.UserService;
import com.augmentum.oes.util.PropertyUtil;
import com.augmentum.oes.util.SessionUtil;
import com.augmentum.oes.util.StringUtil;
import com.augmentum.oes.util.TokenUtil;

@Controller
@RequestMapping(value = Constants.APP_URL_PREFIX)
public class UserController extends BaseController {

    private final static String USER_LOGIN_JSP = "login";
    private final static String USER_LOGIN_PAGE = "login";
    private final static String USER_DETAIL_JSP = "user/userdetail";
    private final static String USER_DETAIL_PAGE = "userdetail";
    private final static String CHANGE_PASSWORD_JSP = "user/changepassword";
    private final static String CHANGE_PASSWORD_PAGE = "tochangepassword";

    private static final int COOKIE_TIME = 60 * 60 * 24 * 7;

    private static final String UPDATE_SUCCESS = "Update Success!";
    private static final String USERNAME = "userName";
    private static final String PASSWORD = "password";
    private static final String USER_NAME = "username";
    private static final String AVERA_IMAGE = "/avera_image/";
    private static final String UPLOADRESULT = "uploadresult";
    private static final String FILEURL = "fileUrl";
    private static final String UPLOAD_PATH = "uploadPath";
    private static final String TO_JSON_LIST = "tojsonlist.action";
    private static final String SAVE_NAME = "saveName";

    @Resource
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public UserController() {
        super();
    }

    @RequestMapping(value = "login")
    public ModelAndView login(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        if (this.getSession(Constants.USER) != null) {
            modelAndView.setView(this.getRedirectView(TO_JSON_LIST));
        } else {
            modelAndView.setViewName(USER_LOGIN_JSP);
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(USERNAME)) {
                        SessionUtil.addSession(USER_NAME, cookie.getValue());
                    }
                    if (cookie.getName().equals(PASSWORD)) {
                        SessionUtil.addSession(PASSWORD, cookie.getValue());
                    }
                }
            }
        }
        return modelAndView;
    }

    @RequestMapping(value = { "showlogin" }, method = RequestMethod.POST)
    public ModelAndView showLogin(@RequestParam(value = "userName") String userName,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "remeberme", required = false) String remember, HttpServletResponse response,
            HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            User user = null;
            user = userService.login(userName, password);
            user.setPassword(null);
            this.addSession(Constants.USER, user);
            if (!StringUtil.isEmpty(remember)) {
                Cookie userNameCookie = new Cookie(USERNAME, userName);
                Cookie passwordCookie = new Cookie(PASSWORD, password);
                userNameCookie.setMaxAge(COOKIE_TIME);
                passwordCookie.setMaxAge(COOKIE_TIME);
                userNameCookie.setPath("/");
                passwordCookie.setPath("/");
                response.addCookie(userNameCookie);
                response.addCookie(passwordCookie);
            } else if (StringUtil.isEmpty(remember)) {
                Cookie userNameCookie = new Cookie(USERNAME, userName);
                Cookie passwordCookie = new Cookie(PASSWORD, password);
                userNameCookie.setMaxAge(0);
                passwordCookie.setMaxAge(0);
                userNameCookie.setPath("/");
                passwordCookie.setPath("/");
                response.addCookie(userNameCookie);
                response.addCookie(passwordCookie);
            }
            modelAndView.setView(new RedirectView(TO_JSON_LIST));
        } catch (ParameterException e) {
            e.printStackTrace();
            this.addSession(Constants.ERROR_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(USER_LOGIN_PAGE));
        } catch (ServiceException e) {
            e.printStackTrace();
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(USER_LOGIN_PAGE));
        }
        return modelAndView;
    }

    @RequestMapping(value = "userdetail")
    public ModelAndView userDetail() {
        User user = null;
        ModelAndView modelAndView = new ModelAndView();
        try {
            int id = ((User) this.getSession(Constants.USER)).getId();
            user = userService.getById(id);
            this.addSession("user", user);
            modelAndView.setViewName(USER_DETAIL_JSP);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            modelAndView.setView(new RedirectView(TO_JSON_LIST));
        } catch (ParameterException e) {
            e.printStackTrace();
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(TO_JSON_LIST));
        }
        return modelAndView;
    }

    @RequestMapping(value = "tochangepassword")
    public ModelAndView toChangePassword() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(CHANGE_PASSWORD_JSP);
        return modelAndView;
    }

    @RequestMapping(value = "changepassword")
    public ModelAndView changePassword(@RequestParam(value = "password") String password) {
        ModelAndView modelAndView = new ModelAndView();
        int id = ((User) this.getSession(Constants.USER)).getId();

        try {
            User user = userService.getById(id);
            user.setPassword(password);
            userService.changePassword(user);
            this.addSession(Constants.SUCCESS_MSG, UPDATE_SUCCESS);
            modelAndView.setView(new RedirectView(CHANGE_PASSWORD_PAGE));
        } catch (ParameterException e) {
            e.printStackTrace();
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setView(new RedirectView(USER_DETAIL_JSP));
        }
        return modelAndView;
    }

    @RequestMapping(value = "uploadimg")
    public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws ParameterException {
        ModelAndView modelAndView = new ModelAndView();
        String path = PropertyUtil.getProperties(UPLOAD_PATH);
        String fileName = file.getOriginalFilename();
        String saveName = TokenUtil.getToken() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        File targetFile = new File(path, saveName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            modelAndView.setView(this.getRedirectView(USER_DETAIL_PAGE + "?" + Math.random()));
        }
        this.addSession(SAVE_NAME, saveName);
        this.addSession(FILEURL, PropertyUtil.getStaticPath() + AVERA_IMAGE + saveName);
        modelAndView.setView(this.getRedirectView(USER_DETAIL_PAGE + "?" + Math.random()));
        return modelAndView;
    }

    @RequestMapping(value = "viewupload")
    public ModelAndView viewUpload() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(UPLOADRESULT);
        return modelAndView;
    }

    @RequestMapping(value = "saveupload")
    public ModelAndView saveUpload(@RequestParam(value = "filename") String saveName) {
        ModelAndView modelAndView = new ModelAndView();
        int id = ((User) this.getSession(Constants.USER)).getId();
        User user = null;
        try {
            user = userService.getById(id);
            user.setPhotoPath(saveName);
            userService.update(user);
            modelAndView.setView(this.getRedirectView(USER_DETAIL_PAGE + "?" + Math.random()));
        } catch (ParameterException e) {
            modelAndView.setView(this.getRedirectView(USER_DETAIL_PAGE + "?" + Math.random()));
        }
        return modelAndView;
    }
}
